package com.iot.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.iot.manage.pojo.Area;
import com.iot.manage.pojo.Device;
import com.iot.manage.result.Code;
import com.iot.manage.result.Result;
import com.iot.manage.service.AreaService;
import com.iot.manage.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 区域管理控制层
 *
 * @author zhuzhi
 */
@RestController
@RequestMapping("/api/private/v1")
public class AreaController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AreaService areaService;

    /**
     * 查询区域信息列表
     *
     * @param token
     * @param query 模糊查询关键字
     * @param pagenum 当前页
     * @param pagesize 每页条数
     * @return
     */
    @GetMapping("/findAreaList")
    public Result findAreaList(
            @RequestHeader("token") String token,
            @RequestParam("query") String query,
            @RequestParam("pagenum") int pagenum,
            @RequestParam("pagesize") int pagesize) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<Area> areaList;
        int areaTotal;
        try{
            areaList = areaService.findAreaList(query,pagenum,pagesize);
            areaTotal = areaService.countAreaList(query);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total",areaTotal);
        map.put("pagenum",pagenum);
        map.put("areaList",areaList);
        return result.build(map, Code.S200);
    }

    /**
     * 新增区域信息
     *
     * @param token
     * @param params 区域信息参数
     * @return
     */
    @PostMapping("/addArea")
    public Result addArea(
            @RequestHeader("token") String token,
            @RequestBody JSONObject params) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            if(null != findAreaByIdOrName(token,params.getString("areaName")).getData()){
                return result.build(null, Code.D412);
            }
            params.put("areaId", UUID.randomUUID().toString().replace("-", ""));
            areaService.addArea(params);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     * 根据区域ID或区域名称查询区域信息
     *
     * @param token
     * @param params 区域ID或区域名称
     * @return
     */
    @GetMapping("/findAreaById/{params}")
    public Result findAreaByIdOrName(
            @RequestHeader("token") String token,
            @PathVariable("params") String params){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        Area area;
        try{
            area = areaService.findAreaByIdOrName(params);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(area, Code.S200);
    }

    /**
     * 修改区域信息
     *
     * @param token
     * @param params 区域信息参数
     * @return
     */
    @PutMapping("/updateAreaInfo/{oldAreaName}")
    public Result updateAreaInfo(
            @RequestHeader("token") String token,
            @PathVariable("oldAreaName") String oldAreaName,
            @RequestBody JSONObject params){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            if (!(oldAreaName.equals(params.get("areaName")))){
                if(null != findAreaByIdOrName(token,params.getString("areaName")).getData()){
                    return result.build(null, Code.D412);
                }
            }
            areaService.updateAreaInfo(params);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     *删除区域信息
     *
     * @param token
     * @param areaId 区域ID
     * @return
     */
    @DeleteMapping("/deleteAreaById/{areaId}")
    public Result deleteAreaById(
            @RequestHeader("token") String token,
            @PathVariable("areaId") String areaId) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            areaService.deleteAreaById(areaId);
            areaService.deleteRelevancyAppById(areaId);
            areaService.deleteRelevancyDeviceById(areaId);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     * 查询全部设备模型
     *
     * @param token
     * @return
     */
    @GetMapping("/findAllAllotDevice")
    public Result findAllAllotDevice(
            @RequestHeader("token") String token) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<Device> deviceList;
        try {
            deviceList = areaService.findAllAllotDevice();
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(deviceList, Code.S200);
    }

    /**
     * 根据区域ID查询已分配的设备模型
     *
     * @param token
     * @param areaId 区域ID
     * @return
     */
    @GetMapping("/findAllotDeviceById/{areaId}")
    public Result findAllotDeviceById(
            @RequestHeader("token") String token,
            @PathVariable("areaId") String areaId) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<String> deviceIdsList;
        try {
            deviceIdsList = areaService.findAllotDeviceById(areaId);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(deviceIdsList, Code.S200);
    }

    /**
     * 保存分配的设备模型
     *
     * @param token
     * @param params 分配的设备模型信息
     * @return
     */
    @PostMapping("/saveDeviceToArea")
    public Result saveDeviceToArea(
            @RequestHeader("token") String token,
            @RequestBody JSONObject params) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<Map<String,String>> list = new ArrayList<>();
        try{
            //删除该区域已分配的设备模型
            areaService.deleteDeviceOfAllotById(params.getString("areaId"));
            String appIdsStr = params.getString("deviceIds").substring(1, params.getString("deviceIds").length() - 1);
            if (!("".equals(appIdsStr))){
                String[] areaIdsArr = appIdsStr.replaceAll(" ","").split(",");
                for (int i = 0; i < areaIdsArr.length; i++) {
                    Map<String,String> map = new HashMap<>();
                    map.put("areaId",params.getString("areaId"));
                    map.put("deviceId",areaIdsArr[i]);
                    list.add(map);
                }
                areaService.addDeviceOfAllotById(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S211);
    }
}
